import React, { useState, useCallback, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

const Home: React.FC = () => {
  const navigate = useNavigate();
  const [isCompressing, setIsCompressing] = useState(false);
  const [progress, setProgress] = useState(0);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [outputPath, setOutputPath] = useState<string>('');

  // 清理状态的函数
  const resetState = useCallback(() => {
    setSelectedFile(null);
    setOutputPath('');
    setProgress(0);
    setIsCompressing(false);
  }, []);

  // 管理压缩进度监听器
  useEffect(() => {
    const handleProgress = (_, progress: number) => {
      setProgress(progress);
    };

    if (isCompressing) {
      window.ipcRenderer.on('compression-progress', handleProgress);
    }

    return () => {
      window.ipcRenderer.off('compression-progress', handleProgress);
    };
  }, [isCompressing]);

  // 处理文件拖放
  const handleDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    const file = e.dataTransfer.files[0];
    if (file && file.type.startsWith('video/')) {
      setSelectedFile(file);
    }
  }, []);

  // 处理文件选择
  const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file && file.type.startsWith('video/')) {
      setSelectedFile(file);
    }
  }, []);

  // 处理视频压缩
  const handleOutputPathSelect = useCallback(async () => {
    try {
      const path = await window.ipcRenderer.invoke('select-save-path');
      if (path) {
        setOutputPath(path);
      }
    } catch (error) {
      alert('选择保存路径失败');
    }
  }, []);

  const handleStartCompression = async () => {
    if (!selectedFile || !outputPath) {
      alert('请选择视频文件和输出路径');
      return;
    }

    const filePath = selectedFile.path;
    setIsCompressing(true);
    setProgress(0);

    try {

      // 发送压缩请求
      const result = await window.ipcRenderer.invoke('compress-video', filePath, outputPath);

      if (result.success) {
        const { comparison } = result;
        const message = `视频压缩完成！\n\n压缩前：\n- 文件大小：${comparison.original.size}MB\n- 分辨率：${comparison.original.resolution}\n- 比特率：${comparison.original.bitrate}kbps\n\n压缩后：\n- 文件大小：${comparison.compressed.size}MB\n- 分辨率：${comparison.compressed.resolution}\n- 比特率：${comparison.compressed.bitrate}kbps\n\n压缩率：${comparison.compressionRatio}%`;
        alert(message);
        // 使用统一的状态重置函数
        resetState();
      } else {
        throw new Error(result.error);
      }
    } catch (error) {
      alert(`压缩失败: ${error.message}`);
    } finally {
      // 重置压缩状态
      setIsCompressing(false);
      setProgress(0);
    }
  };

  return (
    <div className="home-container">
      <h1>欢迎使用视频播放器</h1>
      <div
        className="upload-area"
        onDrop={handleDrop}
        onDragOver={(e) => e.preventDefault()}
      >
        <input
          type="file"
          accept="video/*"
          onChange={handleFileSelect}
          style={{ display: 'none' }}
          id="video-input"
        />
        <label htmlFor="video-input" className="upload-label">
          {isCompressing ? (
            <div className="compression-status">
              <p>正在压缩视频... {progress}%</p>
              <div className="progress-bar">
                <div className="progress" style={{ width: `${progress}%` }} />
              </div>
            </div>
          ) : (
            <>
              <p>拖放视频文件到这里</p>
              <p>或点击选择文件</p>
            </>
          )}
        </label>
      </div>
      <div className="file-info">
        {selectedFile && (
          <p className="selected-file">已选择文件: {selectedFile.name}</p>
        )}
        <div className="output-path-selector">
          <label>输出路径：</label>
          <div className="path-display">
            <span>{outputPath || '未选择保存路径'}</span>
            <button
              onClick={handleOutputPathSelect}
              className="select-path-button"
              type="button"
            >
              选择保存位置
            </button>
          </div>
        </div>
      </div>
      <div className="action-buttons">
        <button
          onClick={handleStartCompression}
          className="primary-button"
          disabled={isCompressing || !selectedFile || !outputPath}
        >
          开始压缩
        </button>
        <button
          onClick={() => navigate('/videos')}
          className="primary-button"
        >
          浏览视频
        </button>
      </div>
    </div>
  );
};

export default Home;